package cn.fastoo.common.sampleframe.search;

import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Field;
import java.util.Iterator;


public class SearchArgumentsResolver implements HandlerMethodArgumentResolver  {

	@Override
	public boolean supportsParameter(MethodParameter parameter) { 
		return parameter.getParameterType().equals(Search.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		String objName = "search_";
		Object o = BeanUtils.instantiate(parameter.getParameterType());
		Search search = (Search)o;
		StringBuffer key;
		String[] value;
		Field[] frr = parameter.getParameterType().getDeclaredFields();
		for (Iterator<String> itr = webRequest.getParameterNames(); itr.hasNext();) {
			key = new StringBuffer(itr.next());
			if(key.indexOf(objName)==-1){
				continue;
			}
			value = webRequest.getParameterValues(key.toString());
			search.addSearchFilter(key.substring(objName.length(),key.length()), value[0]);
		}
		return o;
	}
	
	 
}